#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sqlite3.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define  N  16
#define  R  1   //  user register
#define  L  2   //  user login
#define  Q  3   //  query word
#define  H  4   //  history record

typedef struct{
	int type;
	char name[N];
	char data[256];   // password or word or remark
}MSG;

void do_register(int sockfd, MSG *msg);
int do_login(int sockfd, MSG *msg);
void login_ok(int sockfd, MSG *msg);
void do_query(int sockfd, MSG *msg);
void do_history(int sockfd, MSG *msg);

int main(int argc, char *argv[])
{
	if(argc < 3){
		printf("Usage : %s <serv_ip> <serv_port>\n", argv[0]);
		exit(-1);
	}
	int sockfd = 0;
	if(-1 == (sockfd = socket(AF_INET, SOCK_STREAM, 0))){
		perror("fail to socket");
		exit(-1);
	}
	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	server_addr.sin_port = htons(atoi(argv[2]));
	
	if(-1 == connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr))){
		perror("fail to connect");
		exit(-1);
	}
	MSG msg;
	int choose = 0;
	while(1)
	{
		printf("************************************\n");
		printf("* 1: register   2: login   3: quit *\n");
		printf("************************************\n");
		printf("please choose : ");
		scanf("%d", &choose);
		switch(choose){
			case 1:
				do_register(sockfd, &msg);
				break;
			case 2:
                //执行登录函数，执行完毕后通过返回值决定是否要跳转到下一个菜单
				if(do_login(sockfd, &msg) == 1){
					login_ok(sockfd, &msg);
				}
				break;
			case 3:
				close(sockfd);
				exit(0);
		}
	}
	return 0;
}

void login_ok(int sockfd, MSG *msg){
	int choose = 0;
	while(1){
		printf("************************************\n");
		printf("* 1: query   2: history   3: quit  *\n");
		printf("************************************\n");
		printf("please choose : ");
		scanf("%d", &choose);
		switch(choose){
			case 1:
				do_query(sockfd, msg);
				break;
			case 2:
				do_history(sockfd, msg);
				break;
			case 3:
				return;
		}
	}
}

void do_register(int sockfd, MSG *msg){
}

int do_login(int sockfd, MSG *msg){
}

void do_query(int sockfd, MSG *msg){
}

void do_history(int sockfd, MSG *msg){
}